import jwt from "jsonwebtoken";
import type Typings from "../typings";

// 密钥串
const secretKey = "xt-node-service";

// 生成 JWT
export const getToken = (payload: Typings.Common.plainObj = {}) => {
  return new Promise((resolve, reject) => {
    try {
      const token: string = jwt.sign(payload, secretKey, { expiresIn: "24h" });
      resolve(`Bearer ${token}`);
    } catch (err) {
      reject(err);
    }
  });
};

// 验证 JWT
export const verifyToken = (token: string = "") => {
  const _token = token.split("Bearer ").reverse()[0];
  return new Promise((resolve, reject) => {
    jwt.verify(_token, secretKey, (err, decoded) => {
      if (err) {
        reject(`Token verification failed: ${err}`);
      } else {
        resolve(decoded);
      }
    });
  });
};
